const fs = require('fs');

function addMapping(router, mapping) {
	for (var url in mapping) {
		if (url.startsWith('GET ')) {
			var path = url.substring(4);
			router.get(path, mapping[url]);
			console.log(`register URL mapping: GET ${path}`);
		} else if (url.startsWith('POST ')) {
			var path = url.substring(5);
			router.post(path, mapping[url]);
			console.log(`register URL mapping: POST ${path}`);
		} else {
			console.log(`invalid URL: ${url}`);
		}
	}
}

function addControllers(router) {
	var files = fs.readdirSync(__dirname + '/controllers');
	var js_files = files.filter((f) => {
		return f.endsWith('.js');
	});

	for (var f of js_files) {
		console.log(`process controller: ${f}...`);
		let mapping = require(__dirname + '/controllers/' + f);
		addMapping(router, mapping);
	}
}

function addUploadFile(router) {
	//加载koa-multer模块
	const multer = require('koa-multer');
	//文件上传
  //配置
	var storage = multer.diskStorage({
		//文件保存路径
		destination: function (req, file, cb) {
			cb(null, 'public/uploads/')
		},
		//修改文件名称
		filename: function (req, file, cb) {
			var fileFormat = (file.originalname).split(".");
			cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
		}
	});
	//加载配置
	var upload = multer({ storage: storage });
	//路由
	router.post('/api/upload', upload.single('image'), async (ctx, next) => {
		ctx.body = {
			filename: ctx.req.file.filename//返回文件名
		}
	});
	console.log(`register URL mapping: POST /api/upload`);
}


module.exports = function (dir) {
	let
		controllers_dir = dir || 'controllers', // 如果不传参数，扫描目录默认为'controllers'
		router = require('koa-router')();
	addControllers(router, controllers_dir);
	addUploadFile(router);
	return router.routes();
};